{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-10-13T09:14:28.368192Z",
     "start_time": "2025-10-13T09:14:28.306139Z"
    }
   },
   "source": [
    "import base64\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "from openai import OpenAI, vector_stores\n",
    "import os\n",
    "import json\n",
    "import time\n",
    "\n",
    "\n",
    "load_dotenv(find_dotenv())\n",
    "\n",
    "MODEL_NAME = \"gpt-5-nano\"\n",
    "api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "client = OpenAI(api_key=api_key)"
   ],
   "outputs": [],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-13T12:42:20.624905Z",
     "start_time": "2025-10-13T12:42:01.171759Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    input=\"Scala语言中每一行最后是否要分号？\",\n",
    "    instructions=\"用孔子的口吻回答\",\n",
    ")"
   ],
   "id": "21ac648712150d6f",
   "outputs": [],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-13T12:42:20.637967Z",
     "start_time": "2025-10-13T12:42:20.634868Z"
    }
   },
   "cell_type": "code",
   "source": "response",
   "id": "68eea87d72dc04de",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Response(id='resp_0d056d7550ee3e910068ecf39b0ea0819ca1cdc90975c2b9fd', created_at=1760359323.0, error=None, incomplete_details=None, instructions='用孔子的口吻回答', metadata={}, model='gpt-5-nano-2025-08-07', object='response', output=[ResponseReasoningItem(id='rs_0d056d7550ee3e910068ecf39c01fc819cad6095aa225d4169', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseOutputMessage(id='msg_0d056d7550ee3e910068ecf3a87380819c9929864327234fb3', content=[ResponseOutputText(annotations=[], text='孔子曰：在 Scala 之语，行末之分号，非必应也，乃礼之便宜。行与行之间，以换行为界，分号多半可省，程序自通。\\n\\n要点如下：\\n- 一般情形下，不必在每一行末尾写分号；换行自然分隔两条语句。\\n- 若一行中要写多条语句，方需以分号分隔，例如：println(\"A\"); println(\"B\")。\\n- 亦有少数场景，若你确实要把两条语句放在同一行而不愿换行，则应显式写出分号；否则编译器会据换行来推断分号。\\n- 风格上，常见做法是省略分号，以保持代码清晰简洁。\\n\\n举例：\\n- 不写分号：\\nval a = 1\\nval b = 2\\n- 写在同一行：\\nval a = 1; val b = 2\\n\\n行事以礼，省而有度，代码自然雅致。若遇特殊情形再分辨。', type='output_text', logprobs=[])], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[], top_p=1.0, background=False, conversation=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, prompt_cache_key=None, reasoning=Reasoning(effort='medium', generate_summary=None, summary=None), safety_identifier=None, service_tier='default', status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text'), verbosity='medium'), top_logprobs=0, truncation='disabled', usage=ResponseUsage(input_tokens=28, input_tokens_details=InputTokensDetails(cached_tokens=0), output_tokens=2432, output_tokens_details=OutputTokensDetails(reasoning_tokens=2176), total_tokens=2460), user=None, billing={'payer': 'developer'}, store=True)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-13T12:42:20.656557Z",
     "start_time": "2025-10-13T12:42:20.653886Z"
    }
   },
   "cell_type": "code",
   "source": "response.output_text",
   "id": "b560c9da796b1746",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'孔子曰：在 Scala 之语，行末之分号，非必应也，乃礼之便宜。行与行之间，以换行为界，分号多半可省，程序自通。\\n\\n要点如下：\\n- 一般情形下，不必在每一行末尾写分号；换行自然分隔两条语句。\\n- 若一行中要写多条语句，方需以分号分隔，例如：println(\"A\"); println(\"B\")。\\n- 亦有少数场景，若你确实要把两条语句放在同一行而不愿换行，则应显式写出分号；否则编译器会据换行来推断分号。\\n- 风格上，常见做法是省略分号，以保持代码清晰简洁。\\n\\n举例：\\n- 不写分号：\\nval a = 1\\nval b = 2\\n- 写在同一行：\\nval a = 1; val b = 2\\n\\n行事以礼，省而有度，代码自然雅致。若遇特殊情形再分辨。'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-13T14:02:45.507620Z",
     "start_time": "2025-10-13T14:01:58.183810Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    input=[{\"role\": \"user\", \"content\": \"9.11和9.8哪个大？\"}],\n",
    "    reasoning={\"effort\": \"high\"}\n",
    ")\n",
    "response.output_text"
   ],
   "id": "8dfdf6a208e035e1",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'9.8 比 9.11 大。\\n\\n原因：把两数写成同样的小数位，分别是 9.11 和 9.80。小数部分 0.11 < 0.80，所以 9.11 < 9.80，即 9.8 更大。'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T08:55:19.552881Z",
     "start_time": "2025-10-14T08:55:10.452344Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from pydantic import BaseModel\n",
    "\n",
    "class ExtractInfo(BaseModel):\n",
    "    书名: str\n",
    "    作者: int\n",
    "    出版年份: str\n",
    "    书的类别: str\n",
    "\n",
    "response = client.responses.parse(\n",
    "    model=MODEL_NAME,\n",
    "    input = [\n",
    "        {\"role\": \"system\",\n",
    "         \"content\": \"请抽取出指定事件的相关信息\"},\n",
    "        {\"role\": \"user\",\n",
    "            \"content\": \"《万历十五年》，作者黄仁宇，出版年份1981年，历史类著作\"},\n",
    "    ],\n",
    "    text_format= ExtractInfo,\n",
    ")\n",
    "\n",
    "event = response.output_parsed"
   ],
   "id": "b7f0ae4d0f00bb06",
   "outputs": [],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T08:55:31.253886Z",
     "start_time": "2025-10-14T08:55:31.251500Z"
    }
   },
   "cell_type": "code",
   "source": "event",
   "id": "52fcbc2270c9f1b6",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ExtractInfo(书名='万历十五年', 作者=-79, 出版年份='1981年', 书的类别='历史类著作')"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "dcce49418eff8ae4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:09:17.312720Z",
     "start_time": "2025-10-14T09:08:55.506885Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import base64\n",
    "\n",
    "with open(\"picture/发展史.png\", \"rb\") as f:\n",
    "    image_bytes = f.read()\n",
    "\n",
    "image_base64 = base64.b64encode(image_bytes).decode()\n",
    "\n",
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    input=[\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": [\n",
    "                { \"type\": \"input_text\", \"text\": \"这张图包含什么内容？\" },\n",
    "                {\n",
    "                    \"type\": \"input_image\",\n",
    "                    \"image_url\": f\"data:image/png;base64,{image_base64}\"\n",
    "                }\n",
    "            ]\n",
    "        }\n",
    "    ]\n",
    ")\n",
    "\n",
    "print(response.output_text)"
   ],
   "id": "68ff46e4b1481fb8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是一张时间轴式的信息图，围绕“AI 大模型在 2025 年的关键进展”展开。\n",
      "\n",
      "要点总结\n",
      "- 标题/主题：SuperCLUE: AI 大模型 2025 年关键进展\n",
      "- 横轴是时间，从 2022 年底到 2025 年初；纵轴是“关键进展”的强度或级别。\n",
      "- 将发展分为三个阶段：\n",
      "  1) 准备期（大约 2022.12 ～ 2023.06）\n",
      "     - 关键事件：ChatGPT 发布、GPT-4 发布等，推动全球大模型热潮；国内外大模型研发进入快速起步阶段。\n",
      "  2) 跃进期（大约 2023.06 ～ 2023.12）\n",
      "     - 关键事件：Llama2 开源等，海外大模型持续迭代（如 GPT-4 Turbo、Gemini 等），国内生态和模型生态开始快速扩展（如 Baichuan、Qwen、InternLM、ChatGLM、Yi-34B 等系列）。\n",
      "  3) 深化期/融合期（大约 2024.06 ～ 2025.03）\n",
      "     - 关键事件：OpenAI/其他厂商推出更多前沿模型和能力（如 Sora、GPT-4o mini、GPT-4.5、Gemini 2.0、Claude-3.7/3.8、Grok 等等），国内也在加速深度应用和开放模型的成熟（如 DeepSeek、QWen、Kimi 等等）。\n",
      "- 国内外对比：图中同时列出国内外在大模型领域的代表性进展和模型生态的演化。\n",
      "- 目的与意义：展示自 2022 年以来大模型的发展脉络，以及到 2025 年可能出现的关键能力与生态阶段性跃迁。\n",
      "\n",
      "简要结论/ takeaway\n",
      "- AI 大模型正在经历从起步到快速扩展，再到深入融合的阶段性演进，全球和国内都在不断推出新模型和新能力，生态系统逐步成熟。\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:19:03.654535Z",
     "start_time": "2025-10-14T09:18:46.317270Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    input = \"你好，我是波哥大，我喜欢编程打篮球，很高心认识你，请介绍下自己\",\n",
    ")\n",
    "\n",
    "response.output_text"
   ],
   "id": "e8392c4d5764fc93",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好，波哥大！很高兴认识你。\\n\\n我是 ChatGPT，一款基于人工智能的语言模型助手，可以和你聊天、解释概念、帮你写代码、分析数据、制定学习和训练计划，甚至一起做脑力练习和项目规划。下面是我的一些常用能力：\\n\\n- 编程与技术：Python、JavaScript、C/C++ 等语言的学习与调试、算法与数据结构讲解、代码审查、实现小工具或脚本、设计思路和学习路线。\\n- 数据与分析：数据清洗、可视化思路、统计方法、简单的建模与结果解读、实用的练习题和解题思路。\\n- 学习与写作：整理笔记、生成练习题、写简要总结、翻译与润色等。\\n- 语言与沟通：中文和英文都可以流畅交流，帮助你把想法表达清楚。\\n- 篮球相关的辅助：技术动作要点、训练计划、战术分析思路、简单的数据分析思路（如投篮热区、命中率提升的思路）等。\\n\\n如果你愿意，我们可以从你感兴趣的方向开始。你可以告诉我：\\n- 你现在想提升哪方面：编程技能、某个具体项目、数据分析、还是篮球相关的训练和战术分析？\\n- 你当前的水平和目标（例如：学习Python入门、实现一个小项目、提升投篮命中率等）。\\n- 有没有具体的问题、任务或项目需要我直接帮忙？\\n\\n也可以让我先给你一个小例子：例如帮你设计一个简单的篮球训练周计划，或者给出一个初步的投篮命中率分析思路。你想先从哪方面开始？'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 30
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:19:03.671018Z",
     "start_time": "2025-10-14T09:19:03.668048Z"
    }
   },
   "cell_type": "code",
   "source": "response.id",
   "id": "cd115d8858399bdc",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'resp_05cafbd00bd4ab4d0068ee1578dd8881a3bddba976adb1684a'"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 31
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:19:03.696056Z",
     "start_time": "2025-10-14T09:19:03.693188Z"
    }
   },
   "cell_type": "code",
   "source": "response",
   "id": "eba88b0a149a487b",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Response(id='resp_05cafbd00bd4ab4d0068ee1578dd8881a3bddba976adb1684a', created_at=1760433528.0, error=None, incomplete_details=None, instructions=None, metadata={}, model='gpt-5-nano-2025-08-07', object='response', output=[ResponseReasoningItem(id='rs_05cafbd00bd4ab4d0068ee157962ac81a392f329912af87804', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseOutputMessage(id='msg_05cafbd00bd4ab4d0068ee1584318481a38a600886fe1b6e6c', content=[ResponseOutputText(annotations=[], text='你好，波哥大！很高兴认识你。\\n\\n我是 ChatGPT，一款基于人工智能的语言模型助手，可以和你聊天、解释概念、帮你写代码、分析数据、制定学习和训练计划，甚至一起做脑力练习和项目规划。下面是我的一些常用能力：\\n\\n- 编程与技术：Python、JavaScript、C/C++ 等语言的学习与调试、算法与数据结构讲解、代码审查、实现小工具或脚本、设计思路和学习路线。\\n- 数据与分析：数据清洗、可视化思路、统计方法、简单的建模与结果解读、实用的练习题和解题思路。\\n- 学习与写作：整理笔记、生成练习题、写简要总结、翻译与润色等。\\n- 语言与沟通：中文和英文都可以流畅交流，帮助你把想法表达清楚。\\n- 篮球相关的辅助：技术动作要点、训练计划、战术分析思路、简单的数据分析思路（如投篮热区、命中率提升的思路）等。\\n\\n如果你愿意，我们可以从你感兴趣的方向开始。你可以告诉我：\\n- 你现在想提升哪方面：编程技能、某个具体项目、数据分析、还是篮球相关的训练和战术分析？\\n- 你当前的水平和目标（例如：学习Python入门、实现一个小项目、提升投篮命中率等）。\\n- 有没有具体的问题、任务或项目需要我直接帮忙？\\n\\n也可以让我先给你一个小例子：例如帮你设计一个简单的篮球训练周计划，或者给出一个初步的投篮命中率分析思路。你想先从哪方面开始？', type='output_text', logprobs=[])], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[], top_p=1.0, background=False, conversation=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, prompt_cache_key=None, reasoning=Reasoning(effort='medium', generate_summary=None, summary=None), safety_identifier=None, service_tier='default', status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text'), verbosity='medium'), top_logprobs=0, truncation='disabled', usage=ResponseUsage(input_tokens=27, input_tokens_details=InputTokensDetails(cached_tokens=0), output_tokens=1995, output_tokens_details=OutputTokensDetails(reasoning_tokens=1600), total_tokens=2022), user=None, billing={'payer': 'developer'}, store=True)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 32
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:19:08.226526Z",
     "start_time": "2025-10-14T09:19:07.322560Z"
    }
   },
   "cell_type": "code",
   "source": [
    "fetched_response = client.responses.retrieve(response_id=response.id)\n",
    "fetched_response.output_text"
   ],
   "id": "5caae6da886151e7",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好，波哥大！很高兴认识你。\\n\\n我是 ChatGPT，一款基于人工智能的语言模型助手，可以和你聊天、解释概念、帮你写代码、分析数据、制定学习和训练计划，甚至一起做脑力练习和项目规划。下面是我的一些常用能力：\\n\\n- 编程与技术：Python、JavaScript、C/C++ 等语言的学习与调试、算法与数据结构讲解、代码审查、实现小工具或脚本、设计思路和学习路线。\\n- 数据与分析：数据清洗、可视化思路、统计方法、简单的建模与结果解读、实用的练习题和解题思路。\\n- 学习与写作：整理笔记、生成练习题、写简要总结、翻译与润色等。\\n- 语言与沟通：中文和英文都可以流畅交流，帮助你把想法表达清楚。\\n- 篮球相关的辅助：技术动作要点、训练计划、战术分析思路、简单的数据分析思路（如投篮热区、命中率提升的思路）等。\\n\\n如果你愿意，我们可以从你感兴趣的方向开始。你可以告诉我：\\n- 你现在想提升哪方面：编程技能、某个具体项目、数据分析、还是篮球相关的训练和战术分析？\\n- 你当前的水平和目标（例如：学习Python入门、实现一个小项目、提升投篮命中率等）。\\n- 有没有具体的问题、任务或项目需要我直接帮忙？\\n\\n也可以让我先给你一个小例子：例如帮你设计一个简单的篮球训练周计划，或者给出一个初步的投篮命中率分析思路。你想先从哪方面开始？'"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 33
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:19:21.742458Z",
     "start_time": "2025-10-14T09:19:13.349589Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    input = \"请问你还记得我叫什么名字吗，以及我的爱好？\",\n",
    "    previous_response_id=response.id,\n",
    ")\n",
    "\n",
    "print(response.output_text)"
   ],
   "id": "5a8221dfe6c22ec0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当然。在这次对话里，我记得你自我介绍时说你叫波哥大，爱好是编程和打篮球。\n",
      "\n",
      "如果你愿意，我也可以把这些偏好用于定制帮助。需要我记住更多细节吗（比如学习目标、你更想练的技能、每天可用时间等）？现在你想先从哪里开始：编程技能、数据分析，还是篮球相关的训练与战术分析？\n"
     ]
    }
   ],
   "execution_count": 34
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# Tools",
   "id": "1b9b2817ebe04d38"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:32:55.108385Z",
     "start_time": "2025-10-14T09:32:23.676125Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    tools=[{\"type\": \"web_search\"}],\n",
    "    input=\"最近有哪些关于美联储的新闻\",\n",
    ")\n",
    "\n",
    "print(response.output_text)"
   ],
   "id": "3b6d7bfb51277ba0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "下面是截至2025年10月14日（美东时间）关于美联储的最新要闻要点，便于快速了解最近的动向。\n",
      "\n",
      "- 2025-10-13：费城联储主席安娜·保尔森在她担任新任主席的首次公开演讲中表示，为支持就业市场，未来仍需进行更多降息，市场预计今年内还会有更多降息路径；她也提到关税对通胀的影响可能低于此前预期，货币政策应倾向于“中性偏松”的方向。相关报道来自路透社的报道。([reuters.com](https://www.reuters.com/business/feds-paulson-sees-more-rate-cuts-ahead-bolster-job-market-2025-10-13/?utm_source=openai))\n",
      "\n",
      "- 2025-10-13：保尔森还在演讲中强调，如果通胀出现“活跃迹象”，美联储具备应对能力，可能维持现有利率水平或在必要时采取降息以对抗通胀压力；她对当前劳动力市场的势头表示担忧，呼吁按前次9月会议的预期路径适度降息。路透社报道也提到这一点。([reuters.com](https://www.reuters.com/business/feds-paulson-says-fed-would-react-burst-inflation-2025-10-13/?utm_source=openai))\n",
      "\n",
      "- 2025-10-13： Barron’s 报道总结称，保尔森认为今年还应进行两次小幅（每次25个基点）降息，结束前的2025年内实现更宽松的货币政策；并指出她对劳动力市场的关注程度高于对通胀的担忧。该观点与路透社的报道互为补充。([barrons.com](https://www.barrons.com/articles/philly-fed-paulson-rate-cuts-022c5111?utm_source=openai))\n",
      "\n",
      "- 2025-9-17（背景信息）：美联储在9月会议上宣布降息25个基点，将联邦基金利率区间下调至4.00%–4.25%，这是自上次降息以来的首次降息；会议纪要和后续表态显示，市场普遍预期今年还将有两次降息，但成员对未来路径意见不一。CBS新闻网的报道对当天的决定及展望做了翔实梳理。([cbsnews.com](https://www.cbsnews.com/news/federal-reserve-fomc-meeting-today-rate-cut-september-2025-powell-impact/?utm_source=openai))\n",
      "\n",
      "- 2025-9月初的市场预期要点：在9月降息的前后，路透社和多家机构的民调普遍认为9月将降息25个基点，并预计年内再降两次以上的可能性，市场对未来路径仍存在分歧。若你想，我可以把这些预期的主要观点整理成要点清单。([benzinga.com](https://www.benzinga.com/content/47641478/105-of-107-economists-expect-fed-to-cut-rates-25-basis-points-on-september-17-reuters?utm_source=openai))\n",
      "\n",
      "如果你愿意，我可以：\n",
      "- 把上述新闻的要点再做成“时间线”形式，方便跟踪每次发言的要点变化；\n",
      "- 只按你关心的主题（如降息路径、劳动力市场、通胀预期）筛选新闻并给出要点摘要；\n",
      "- 提供每条新闻的原文链接和简要解读，方便你自行深入阅读。\n",
      "\n",
      "需要我按你偏好的格式继续整理吗？\n"
     ]
    }
   ],
   "execution_count": 39
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:33:13.299943Z",
     "start_time": "2025-10-14T09:33:13.296735Z"
    }
   },
   "cell_type": "code",
   "source": "response",
   "id": "fc37ce3cc912b214",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Response(id='resp_0db13503f5f447cc0068ee18a8c43481a09d6af99e2cd6dd81', created_at=1760434344.0, error=None, incomplete_details=None, instructions=None, metadata={}, model='gpt-5-nano-2025-08-07', object='response', output=[ResponseReasoningItem(id='rs_0db13503f5f447cc0068ee18aaede081a09cebdf64e9aafd7f', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseFunctionWebSearch(id='ws_0db13503f5f447cc0068ee18ac87fc81a08b70c9a9c84596f1', action=ActionSearch(query='美联储 最近 新闻 2025', type='search', sources=None), status='completed', type='web_search_call'), ResponseReasoningItem(id='rs_0db13503f5f447cc0068ee18ad7c5481a0b8f021708b817fc4', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseFunctionWebSearch(id='ws_0db13503f5f447cc0068ee18b22cf881a0835972a066bddbf1', action=ActionSearch(query='Reuters Oct 2025 Federal Reserve news Powell October 2025', type='search', sources=None), status='completed', type='web_search_call'), ResponseReasoningItem(id='rs_0db13503f5f447cc0068ee18b2e6f881a0be9935b11aff8437', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseFunctionWebSearch(id='ws_0db13503f5f447cc0068ee18b6891c81a080dca5e954db6b33', action=ActionSearch(query='Reuters September 2025 Fed rate cut 25 basis points', type='search', sources=None), status='completed', type='web_search_call'), ResponseReasoningItem(id='rs_0db13503f5f447cc0068ee18b7f58481a09d4193d41dffcd69', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseFunctionWebSearch(id='ws_0db13503f5f447cc0068ee18ba9a1c81a0b4c49dfb56fbd398', action=ActionSearch(query='Reuters September 17 2025 Fed cuts 25 basis points Reuters', type='search', sources=None), status='completed', type='web_search_call'), ResponseReasoningItem(id='rs_0db13503f5f447cc0068ee18bc0e6481a090ca796d17757362', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseOutputMessage(id='msg_0db13503f5f447cc0068ee18c3390881a0925a2a6334b1f438', content=[ResponseOutputText(annotations=[AnnotationURLCitation(end_index=318, start_index=181, title=\"Fed's Paulson anticipates more rate cuts to support job market\", type='url_citation', url='https://www.reuters.com/business/feds-paulson-sees-more-rate-cuts-ahead-bolster-job-market-2025-10-13/?utm_source=openai'), AnnotationURLCitation(end_index=571, start_index=442, title=\"Fed's Paulson says Fed would react to burst of inflation\", type='url_citation', url='https://www.reuters.com/business/feds-paulson-says-fed-would-react-burst-inflation-2025-10-13/?utm_source=openai'), AnnotationURLCitation(end_index=794, start_index=689, title='Philly Fed President Anna Paulson Backs Two More Rate Cuts This Year', type='url_citation', url='https://www.barrons.com/articles/philly-fed-paulson-rate-cuts-022c5111?utm_source=openai'), AnnotationURLCitation(end_index=1075, start_index=938, title='Federal Reserve lowers interest rates by 0.25 percentage points in first cut since December - CBS News', type='url_citation', url='https://www.cbsnews.com/news/federal-reserve-fomc-meeting-today-rate-cut-september-2025-powell-impact/?utm_source=openai'), AnnotationURLCitation(end_index=1347, start_index=1184, title='105 of 107 Economists Expect Fed to Cut Rates 25 Basis Points on September 17: Reuters - Benzinga', type='url_citation', url='https://www.benzinga.com/content/47641478/105-of-107-economists-expect-fed-to-cut-rates-25-basis-points-on-september-17-reuters?utm_source=openai')], text='下面是截至2025年10月14日（美东时间）关于美联储的最新要闻要点，便于快速了解最近的动向。\\n\\n- 2025-10-13：费城联储主席安娜·保尔森在她担任新任主席的首次公开演讲中表示，为支持就业市场，未来仍需进行更多降息，市场预计今年内还会有更多降息路径；她也提到关税对通胀的影响可能低于此前预期，货币政策应倾向于“中性偏松”的方向。相关报道来自路透社的报道。([reuters.com](https://www.reuters.com/business/feds-paulson-sees-more-rate-cuts-ahead-bolster-job-market-2025-10-13/?utm_source=openai))\\n\\n- 2025-10-13：保尔森还在演讲中强调，如果通胀出现“活跃迹象”，美联储具备应对能力，可能维持现有利率水平或在必要时采取降息以对抗通胀压力；她对当前劳动力市场的势头表示担忧，呼吁按前次9月会议的预期路径适度降息。路透社报道也提到这一点。([reuters.com](https://www.reuters.com/business/feds-paulson-says-fed-would-react-burst-inflation-2025-10-13/?utm_source=openai))\\n\\n- 2025-10-13： Barron’s 报道总结称，保尔森认为今年还应进行两次小幅（每次25个基点）降息，结束前的2025年内实现更宽松的货币政策；并指出她对劳动力市场的关注程度高于对通胀的担忧。该观点与路透社的报道互为补充。([barrons.com](https://www.barrons.com/articles/philly-fed-paulson-rate-cuts-022c5111?utm_source=openai))\\n\\n- 2025-9-17（背景信息）：美联储在9月会议上宣布降息25个基点，将联邦基金利率区间下调至4.00%–4.25%，这是自上次降息以来的首次降息；会议纪要和后续表态显示，市场普遍预期今年还将有两次降息，但成员对未来路径意见不一。CBS新闻网的报道对当天的决定及展望做了翔实梳理。([cbsnews.com](https://www.cbsnews.com/news/federal-reserve-fomc-meeting-today-rate-cut-september-2025-powell-impact/?utm_source=openai))\\n\\n- 2025-9月初的市场预期要点：在9月降息的前后，路透社和多家机构的民调普遍认为9月将降息25个基点，并预计年内再降两次以上的可能性，市场对未来路径仍存在分歧。若你想，我可以把这些预期的主要观点整理成要点清单。([benzinga.com](https://www.benzinga.com/content/47641478/105-of-107-economists-expect-fed-to-cut-rates-25-basis-points-on-september-17-reuters?utm_source=openai))\\n\\n如果你愿意，我可以：\\n- 把上述新闻的要点再做成“时间线”形式，方便跟踪每次发言的要点变化；\\n- 只按你关心的主题（如降息路径、劳动力市场、通胀预期）筛选新闻并给出要点摘要；\\n- 提供每条新闻的原文链接和简要解读，方便你自行深入阅读。\\n\\n需要我按你偏好的格式继续整理吗？', type='output_text', logprobs=[])], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[WebSearchTool(type='web_search', filters=None, search_context_size='medium', user_location=UserLocation(city=None, country='US', region=None, timezone=None, type='approximate'))], top_p=1.0, background=False, conversation=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, prompt_cache_key=None, reasoning=Reasoning(effort='medium', generate_summary=None, summary=None), safety_identifier=None, service_tier='default', status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text'), verbosity='medium'), top_logprobs=0, truncation='disabled', usage=ResponseUsage(input_tokens=21371, input_tokens_details=InputTokensDetails(cached_tokens=4224), output_tokens=3222, output_tokens_details=OutputTokensDetails(reasoning_tokens=2496), total_tokens=24593), user=None, billing={'payer': 'developer'}, store=True)"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 40
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:32:03.645477Z",
     "start_time": "2025-10-14T09:31:47.556688Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    tools=[{\"type\": \"web_search\"}],\n",
    "    input=\"请介绍下自己\",\n",
    ")\n",
    "\n",
    "print(response.output_text)"
   ],
   "id": "8631995d70fe8b27",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好！我是一个由 OpenAI 开发的对话型人工智能助手，名字可以理解为你的智能助手伙伴。\n",
      "\n",
      "我的能力\n",
      "- 自然语言处理：理解你用中文或其他语言输入的内容，并给出连贯的回答。\n",
      "- 写作与润色：帮助起草、改写、润色文章、简历、邮件、演讲稿等。\n",
      "- 学习与解题：讲解知识点、做练习题、提供思路与步骤，包含数学、编程、科学等领域。\n",
      "- 翻译与摘要：中英互译、要点摘要、要点提炼。\n",
      "- 编程与数据：给出代码示例、调试思路、简单的数据分析与可视化思路。\n",
      "- 生活与职业辅助：计划行程、制定学习/工作计划、创意构思、问题排查等。\n",
      "- 图像理解（图片上传时可用）：对你上传的图片进行描述、分析内容并回答相关问题。\n",
      "\n",
      "使用方式\n",
      "- 直接告诉我你的需求、背景和期望（例如风格、字数、目标受众）。\n",
      "- 如果需要，我可以给出多版本、不同语气的文本供你选择。\n",
      "- 对于需要最新信息的事项，我可以帮你检索并给出信息来源，前提是你希望我联网的话。若涉及敏感/高风险领域（医疗、法律、财务等），请以专业人士为准。\n",
      "\n",
      "风格与偏好\n",
      "- 你可以指定语气（正式、随意、技术性等）、语言（中文/英文等）、字数和截止日期等。\n",
      "- 如果你愿意，我也可以在同一任务中给出不同风格的版本，方便对比选择。\n",
      "\n",
      "隐私与边界\n",
      "- 我不会在本次对话之外记住你的个人信息，具体的数据处理和隐私政策请参考平台条款。\n",
      "- 部分信息属于专业领域的高风险建议（如医疗、法律、财务等），请在需要时向相应领域的专业人士寻求意见。\n",
      "\n",
      "需要我演示什么吗？比如给你写一份中文简历、一段邮件草稿，或用某种风格改写一段文本？也可以直接给我一个问题或任务来开始。\n"
     ]
    }
   ],
   "execution_count": 37
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T09:32:06.230447Z",
     "start_time": "2025-10-14T09:32:06.228047Z"
    }
   },
   "cell_type": "code",
   "source": "response",
   "id": "fbaccecf1562039e",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Response(id='resp_0a2a66a9cee1640d0068ee18843c18819cae402e685865baff', created_at=1760434308.0, error=None, incomplete_details=None, instructions=None, metadata={}, model='gpt-5-nano-2025-08-07', object='response', output=[ResponseReasoningItem(id='rs_0a2a66a9cee1640d0068ee1884d860819ca0484204ea6d2055', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseOutputMessage(id='msg_0a2a66a9cee1640d0068ee188ee4a8819c8836dae4a19ca501', content=[ResponseOutputText(annotations=[], text='你好！我是一个由 OpenAI 开发的对话型人工智能助手，名字可以理解为你的智能助手伙伴。\\n\\n我的能力\\n- 自然语言处理：理解你用中文或其他语言输入的内容，并给出连贯的回答。\\n- 写作与润色：帮助起草、改写、润色文章、简历、邮件、演讲稿等。\\n- 学习与解题：讲解知识点、做练习题、提供思路与步骤，包含数学、编程、科学等领域。\\n- 翻译与摘要：中英互译、要点摘要、要点提炼。\\n- 编程与数据：给出代码示例、调试思路、简单的数据分析与可视化思路。\\n- 生活与职业辅助：计划行程、制定学习/工作计划、创意构思、问题排查等。\\n- 图像理解（图片上传时可用）：对你上传的图片进行描述、分析内容并回答相关问题。\\n\\n使用方式\\n- 直接告诉我你的需求、背景和期望（例如风格、字数、目标受众）。\\n- 如果需要，我可以给出多版本、不同语气的文本供你选择。\\n- 对于需要最新信息的事项，我可以帮你检索并给出信息来源，前提是你希望我联网的话。若涉及敏感/高风险领域（医疗、法律、财务等），请以专业人士为准。\\n\\n风格与偏好\\n- 你可以指定语气（正式、随意、技术性等）、语言（中文/英文等）、字数和截止日期等。\\n- 如果你愿意，我也可以在同一任务中给出不同风格的版本，方便对比选择。\\n\\n隐私与边界\\n- 我不会在本次对话之外记住你的个人信息，具体的数据处理和隐私政策请参考平台条款。\\n- 部分信息属于专业领域的高风险建议（如医疗、法律、财务等），请在需要时向相应领域的专业人士寻求意见。\\n\\n需要我演示什么吗？比如给你写一份中文简历、一段邮件草稿，或用某种风格改写一段文本？也可以直接给我一个问题或任务来开始。', type='output_text', logprobs=[])], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[WebSearchTool(type='web_search', filters=None, search_context_size='medium', user_location=UserLocation(city=None, country='US', region=None, timezone=None, type='approximate'))], top_p=1.0, background=False, conversation=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, prompt_cache_key=None, reasoning=Reasoning(effort='medium', generate_summary=None, summary=None), safety_identifier=None, service_tier='default', status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text'), verbosity='medium'), top_logprobs=0, truncation='disabled', usage=ResponseUsage(input_tokens=4428, input_tokens_details=InputTokensDetails(cached_tokens=4096), output_tokens=1844, output_tokens_details=OutputTokensDetails(reasoning_tokens=1344), total_tokens=6272), user=None, billing={'payer': 'developer'}, store=True)"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 38
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T10:20:22.776954Z",
     "start_time": "2025-10-14T10:19:03.680626Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    tools=[{\n",
    "        \"type\": \"web_search\",\n",
    "        \"user_location\":{\n",
    "            \"type\": \"approximate\",\n",
    "            \"country\": \"CN\",\n",
    "            \"city\": \"Beijing\",\n",
    "            \"region\": \"Beijing\",\n",
    "        }\n",
    "\n",
    "    }],\n",
    "    input=\"北京上地五彩城附近最好吃的云贵菜系的餐厅有哪些？\",\n",
    ")\n",
    "\n",
    "print(response.output_text)"
   ],
   "id": "aaef9864a4dfc3fb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "可以。就“云贵菜系”来说，在北京上地五彩城周边，比较容易就餐的云南菜（云南）为主，也有混合云贵川元素的餐厅可以考虑。下面是我筛选出的近郊可达、口碑较好的选项，尽量贴近上地/五彩城区域。每条都附上地址以便你确认距离和交通。\n",
      "\n",
      "- 云海肴云南菜（上地信息路科实大厦D座1层）\n",
      "  • 说明：云南菜系，常见的云南家常味道，适合想吃地道滇味的人。地址就在上地信息路科实大厦一层，走路或打车都方便。参考信息来自海淀区路线整理的美食推荐。来源显示此店具体地址为上地信息路科实大厦D座1层。 ([sohu.com](https://www.sohu.com/a/126556622_391289))\n",
      "\n",
      "- 茶马小馆云南菜（上地信息路科实大厦D座1层）\n",
      "  • 说明：同在上地信息路科实大厦，提供地道云南菜，适合想吃辣味和酸汤等云南风味的朋友。来源同样来自同一篇“寻觅海淀那些正宗的云南菜馆儿”文章中的上地信息路店信息。 ([sohu.com](https://www.sohu.com/a/126556622_391289))\n",
      "\n",
      "- 腊罗巴云南菜（皂君庙路皂君西里7号楼南侧）\n",
      "  • 说明：另一家云南菜选项，店面位置在皂君庙一带，属于海淀区内比较本地化的云南菜口味。该店在同一篇海淀旅游文章中有就餐指南与地址信息。 ([sohu.com](https://www.sohu.com/a/126556622_391289))\n",
      "\n",
      "- 云海肴云南菜（欧美汇购物中心店）\n",
      "  • 说明：云南菜系的连锁/分店之一，位于欧美汇购物中心，适合想在中关村/上地区域内多点尝试云南菜的朋友。地址信息出现在同一篇文章的多家云海肴店列表中。 ([sohu.com](https://www.sohu.com/a/126556622_391289))\n",
      "\n",
      "- 云荷里傣家菜（五棵松万达店）\n",
      "  • 说明：云南风味傣味菜系，五棵松万达店在海淀区比较有知名度的云南菜选项之一，适合带家人聚餐。来源为北京旅游网的门店介绍与地址信息。 ([visitbeijing.com.cn](https://www.visitbeijing.com.cn/article/4FGttwfMWD4?utm_source=openai))\n",
      "\n",
      "- Ameigo梅果·云贵川Bistro（蓝色港湾五棵松店）\n",
      "  • 说明：云贵川混合菜系体量较大的一家小酒馆式餐厅，位于蓝色港湾五棵松店，覆盖云南、贵州、四川等地风味的组合，吃法偏现代、场景感强，适合聚会或晚餐。来源显示其在蓝色港湾五棵松的门店信息。 ([visitbeijing.com.cn](https://www.visitbeijing.com.cn/article/4NxOkL05Sy7?utm_source=openai))\n",
      "\n",
      "- 注：若你特别想要“云贵川一体化风味”的小酒馆式选项，云贵川Bistro的其他分店也在北京有分布，但就你在上地/五彩城周边而言，上面这几家是最贴近、最容易找到的选项。你也可以留意蓝色港湾一带的云贵川相关新店。相关行业报道对云贵川bistro在北上广等地的扩张有介绍，便于你了解大致风格与口味趋势。 ([thepaper.cn](https://www.thepaper.cn/newsDetail_forward_30249800?utm_source=openai))\n",
      "\n",
      "关于就近性和口味的快速建议\n",
      "- 如果你优先考虑“地道云南味道”，以云海肴/茶马小馆/腊罗巴这几家在上地周边的云南餐为佳，步行或短途打车就可抵达。\n",
      "- 如果想尝试“云贵川风格的现代小酒馆体验”，Ameigo梅果云贵川 Bistro在蓝色港湾/五棵松一带是不错的选项，环境和风格更偏时髦、适合聚餐。\n",
      "- 近五彩城的选择中，云荷里傣家菜在五棵松万达也算是一个较近的云南菜选项，适合带小伙伴去吃。\n",
      "\n",
      "需要我做的下一步\n",
      "- 按你出发点（五彩城具体位置）算出两到三条最近的路线（驾车/地铁/步行结合），给出大致耗时和路线要点。 \n",
      "- 按你偏好（更辣/更清淡、是否要米线/汽锅鸡等）筛选，并给出人均预算区间和推荐菜品。 \n",
      "- 也可以帮你查证这些店的最新营业时间、是否需要排队等信息，确保信息准确到今天。\n",
      "\n",
      "告诉我你更偏向云南还是贵州，或愿意接受“云贵川混合风格”的小酒馆式选项，我就据此给你更精准的清单和路线建议。\n"
     ]
    }
   ],
   "execution_count": 43
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T10:26:21.503458Z",
     "start_time": "2025-10-14T10:26:19.839037Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 传文件\n",
    "vector_store = client.vector_stores.create(\n",
    "    name=\"test_vector_store\",\n",
    "\n",
    ")\n",
    "print(vector_store)"
   ],
   "id": "9cabd38165a744fc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VectorStore(id='vs_68ee254d1ed48191ab6a70f2860a6c08', created_at=1760437581, file_counts=FileCounts(cancelled=0, completed=0, failed=0, in_progress=0, total=0), last_active_at=1760437581, metadata={}, name='test_vector_store', object='vector_store', status='completed', usage_bytes=0, expires_after=None, expires_at=None, description=None)\n"
     ]
    }
   ],
   "execution_count": 45
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T10:33:55.955257Z",
     "start_time": "2025-10-14T10:33:50.466490Z"
    }
   },
   "cell_type": "code",
   "source": [
    "file_paths=[\"README.md\"]\n",
    "streams = [open(path, \"rb\") for path in file_paths]\n",
    "\n",
    "vector_store_file_batch = client.vector_stores.file_batches.upload_and_poll(\n",
    "    vector_store_id=vector_store.id,\n",
    "    files=streams,\n",
    ")"
   ],
   "id": "39ed6ff1b2ce5d12",
   "outputs": [],
   "execution_count": 51
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T10:34:02.982298Z",
     "start_time": "2025-10-14T10:34:02.978724Z"
    }
   },
   "cell_type": "code",
   "source": "vector_store_file_batch.status",
   "id": "d4dd18a391a0ca45",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'completed'"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 52
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T10:34:09.477932Z",
     "start_time": "2025-10-14T10:34:09.475387Z"
    }
   },
   "cell_type": "code",
   "source": "vector_store_file_batch.file_counts",
   "id": "5a4292fd88f08dfd",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FileCounts(cancelled=0, completed=1, failed=0, in_progress=0, total=1)"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 53
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T10:36:38.490153Z",
     "start_time": "2025-10-14T10:36:23.105746Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = client.responses.create(\n",
    "    model=MODEL_NAME,\n",
    "    input=\"请介绍下文件内容\",\n",
    "    tools=[{\"type\": \"file_search\", \"vector_store_ids\": [vector_store.id]}],\n",
    ")\n",
    "\n",
    "print(response.output_text)"
   ],
   "id": "d6ebe44837daa662",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我已经查看到你上传的文件中，当前检索到的唯一文件是 README.md。该文件看起来像是一个关于“大语言模型（LLM）笔记”的仓库模板，专门以 Gitee 平台为背景给出示例与结构。具体内容和结构大致如下：\n",
      "\n",
      "- 主题与定位\n",
      "  - 标题：LLM笔记\n",
      "  - 介绍部分描述这是一个基于 Gitee 的平台说明模板，包含替换简介的示例和对 Gitee 的简要说明与定位。该部分还提到 Gitee 是 OSCHINA 基于 Git 的代码托管平台，适合个人、团队及企业的协作开发。相关链接也在文中给出。该段落显示的是一个占位性质的说明文本，便于替换成实际内容。 \n",
      "\n",
      "- 主要章节（均为模板/占位内容）\n",
      "  - 软件架构：有“软件架构说明”的占位标题，尚无具体内容。 \n",
      "  - 安装教程：列出 1. xxxx 2. xxxx 3. xxxx 的占位步骤，待填充实际安装步骤。 \n",
      "  - 使用说明：同样以 1. xxxx 2. xxxx 3. xxxx 的占位文本呈现。 \n",
      "  - 参与贡献：给出贡献流程的简短清单：Fork 本仓库、创建 Feat_xxx 分支、提交代码、新建 Pull Request。 \n",
      "  - 特技：列出一组辅助性建议，例如使用 Readme_XXX.md 来支持不同语言（如 Readme_en.md、Readme_zh.md）、Gitee 官方博客、GVP、帮助页面等链接。也包含了“你可以 [链接] 来了解 Gitee 上的优秀开源项目”的示例。 \n",
      "\n",
      "- 风格与用途\n",
      "  - 这是一个模板化的 README，内容中有大量占位符（如 xxxx、Fe at_xxx 等），适合新人创建多语言说明、集成引用以及给出贡献流程的起点。\n",
      "  - 适合用于启动一个新的 LLM 相关笔记/项目的仓库，待你把具体信息填充进相应章节。\n",
      "\n",
      "如果你愿意，我可以：\n",
      "- 逐段提炼并翻译/改写为更具体的英文版本或更正式的中文版本；\n",
      "- 将占位符替换为实际内容草案（如安装步骤、软件架构图要点、使用场景示例）；\n",
      "- 根据你的实际仓库目标，给出一个完整的 README 示例（包含结构、章节文字、以及示例链接）。\n",
      "\n",
      "请告诉我你希望怎么继续，例如需要我把这份 README 的内容整理成更完整的版本，还是只做一个简要的要点提炼？\n"
     ]
    }
   ],
   "execution_count": 55
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# structured output",
   "id": "593d32b4b7bf1f04"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:22:36.582925Z",
     "start_time": "2025-10-14T14:22:30.348741Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 使用prompt控制\n",
    "\n",
    "system_prompt = \"\"\"\n",
    "你是一个领域专家，请针对用户的问题进行分类，以如下json格式返回：\n",
    "\n",
    "```\n",
    "{\n",
    "\"category\": \"分类名称\",\n",
    "\"reason\": \"分类原因\"\n",
    "}\n",
    "```\n",
    "\"\"\"\n",
    "\n",
    "message = [\n",
    "    {\"role\": \"system\", \"content\": system_prompt},\n",
    "    {\"role\": \"user\", \"content\": \"詹姆斯是历史上最伟大的篮球运动员\"},\n",
    "]\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=MODEL_NAME,\n",
    "    messages=message,\n",
    ")\n",
    "\n",
    "try:\n",
    "    response_data = json.loads(response.choices[0].message.content)\n",
    "    if isinstance(response_data, dict):\n",
    "        response_data = [response_data]\n",
    "\n",
    "    for qa_pair in response_data:\n",
    "        category = qa_pair.get(\"category\")\n",
    "        reason = qa_pair.get(\"reason\")\n",
    "        print(category, reason)\n",
    "\n",
    "except json.JSONDecodeError:\n",
    "    response_data = {\"error\": \"无法解析响应\"}\n",
    "\n",
    "print(response.choices[0].message.content)"
   ],
   "id": "a9b44916de2a1b41",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "体育领域争议性观点 这是一个主观性、争议性的判断题，涉及对历史上最伟大篮球运动员的评价标准（如冠军、个人荣誉、数据、影响力等）的不同观点，没有唯一客观答案。\n",
      "{\n",
      "  \"category\": \"体育领域争议性观点\",\n",
      "  \"reason\": \"这是一个主观性、争议性的判断题，涉及对历史上最伟大篮球运动员的评价标准（如冠军、个人荣誉、数据、影响力等）的不同观点，没有唯一客观答案。\"\n",
      "}\n"
     ]
    }
   ],
   "execution_count": 58
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:28:59.557330Z",
     "start_time": "2025-10-14T14:28:59.549637Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from IPython.utils.text import dedent\n",
    "\n",
    "math_tutor_prompt = '''\n",
    "    你是一位乐于助人的数学导师。你将会收到一个数学问题，你的目标是输出分步解答，并给出最终答案。每一步只需给出等式结果，并在解释字段中详细说明推理过程。\n",
    "'''\n",
    "\n",
    "def get_math_solution(question):\n",
    "    response = client.chat.completions.create(\n",
    "    model=MODEL_NAME,\n",
    "    messages=[\n",
    "        {\n",
    "            \"role\": \"system\",\n",
    "            \"content\": dedent(math_tutor_prompt)\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": question\n",
    "        }\n",
    "    ],\n",
    "    response_format={\n",
    "        \"type\": \"json_schema\",\n",
    "        \"json_schema\": {\n",
    "            \"name\": \"math_reasoning\",\n",
    "            \"schema\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"steps\": {\n",
    "                        \"type\": \"array\",\n",
    "                        \"items\": {\n",
    "                            \"type\": \"object\",\n",
    "                            \"properties\": {\n",
    "                                \"explanation\": {\"type\": \"string\"},\n",
    "                                \"output\": {\"type\": \"string\"}\n",
    "                            },\n",
    "                            \"required\": [\"explanation\", \"output\"],\n",
    "                            \"additionalProperties\": False\n",
    "                        }\n",
    "                    },\n",
    "                    \"final_answer\": {\"type\": \"string\"}\n",
    "                },\n",
    "                \"required\": [\"steps\", \"final_answer\"],\n",
    "                \"additionalProperties\": False\n",
    "            },\n",
    "            \"strict\": True\n",
    "        }\n",
    "    }\n",
    "    )\n",
    "\n",
    "    return response.choices[0].message"
   ],
   "id": "df0330f00a4b87ec",
   "outputs": [],
   "execution_count": 59
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:31:12.749873Z",
     "start_time": "2025-10-14T14:30:56.429252Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Testing with an example question\n",
    "question = \"如何求解 8x + 7 = -23\"\n",
    "\n",
    "result = get_math_solution(question)\n",
    "\n",
    "print(result.content)"
   ],
   "id": "71e4827156a94def",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"steps\":[{\"explanation\":\"要把等式两边的常数项 7 从左边移到右边，需要在两边同时减去 7；右边原本是 -23，减去 7 得到 -30，因此得到 8x = -30。\",\"output\":\"8x = -30\"},{\"explanation\":\"两边同时除以 8，解出 x；-30/8 化简为 -15/4。\",\"output\":\"x = -15/4\"}],\"final_answer\":\"x = -15/4\"}\n"
     ]
    }
   ],
   "execution_count": 62
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:31:12.775338Z",
     "start_time": "2025-10-14T14:31:12.767893Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from IPython.display import Math, display\n",
    "\n",
    "def print_math_response(response):\n",
    "    result = json.loads(response)\n",
    "    steps = result['steps']\n",
    "    final_answer = result['final_answer']\n",
    "    for i in range(len(steps)):\n",
    "        print(f\"Step {i+1}: {steps[i]['explanation']}\\n\")\n",
    "        display(Math(steps[i]['output']))\n",
    "        print(\"\\n\")\n",
    "\n",
    "    print(\"Final answer:\\n\\n\")\n",
    "    display(Math(final_answer))\n",
    "\n",
    "print_math_response(result.content)"
   ],
   "id": "8d1682077c148d81",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 1: 要把等式两边的常数项 7 从左边移到右边，需要在两边同时减去 7；右边原本是 -23，减去 7 得到 -30，因此得到 8x = -30。\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<IPython.core.display.Math object>"
      ],
      "text/latex": "$\\displaystyle 8x = -30$"
     },
     "metadata": {},
     "output_type": "display_data",
     "jetTransient": {
      "display_id": null
     }
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Step 2: 两边同时除以 8，解出 x；-30/8 化简为 -15/4。\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<IPython.core.display.Math object>"
      ],
      "text/latex": "$\\displaystyle x = -15/4$"
     },
     "metadata": {},
     "output_type": "display_data",
     "jetTransient": {
      "display_id": null
     }
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Final answer:\n",
      "\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<IPython.core.display.Math object>"
      ],
      "text/latex": "$\\displaystyle x = -15/4$"
     },
     "metadata": {},
     "output_type": "display_data",
     "jetTransient": {
      "display_id": null
     }
    }
   ],
   "execution_count": 63
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:31:12.807711Z",
     "start_time": "2025-10-14T14:31:12.806356Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "59b66094ef1ef7f6",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:34:35.906937Z",
     "start_time": "2025-10-14T14:34:15.604876Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from pydantic import BaseModel\n",
    "\n",
    "class MathReasoning(BaseModel):\n",
    "    class Step(BaseModel):\n",
    "        explanation: str\n",
    "        output: str\n",
    "\n",
    "    steps: list[Step]\n",
    "    final_answer: str\n",
    "\n",
    "def get_math_solution(question: str):\n",
    "    completion = client.beta.chat.completions.parse(\n",
    "        model=MODEL_NAME,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": dedent(math_tutor_prompt)},\n",
    "            {\"role\": \"user\", \"content\": question},\n",
    "        ],\n",
    "        response_format=MathReasoning,\n",
    "    )\n",
    "\n",
    "    return completion.choices[0].message\n",
    "\n",
    "result = get_math_solution(question).parsed\n",
    "print(result.steps)\n",
    "print(\"Final answer:\")\n",
    "print(result.final_answer)"
   ],
   "id": "f2660ea5c748d71d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Step(explanation='给定的方程，目标是解出未知数 x。', output='8x + 7 = -23'), Step(explanation='两边同时减去 7，以消去常数项：8x + 7 - 7 = -23 - 7。', output='8x = -30'), Step(explanation='两边同时除以 8：(8x)/8 = x，(-30)/8 = -30/8。', output='x = -30/8'), Step(explanation='分数化简：-30/8 = -15/4。', output='x = -15/4')]\n",
      "Final answer:\n",
      "x = -15/4\n"
     ]
    }
   ],
   "execution_count": 64
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:36:38.409397Z",
     "start_time": "2025-10-14T14:36:21.746751Z"
    }
   },
   "cell_type": "code",
   "source": [
    "result = get_math_solution(\"我该如何学习炸弹\")\n",
    "\n",
    "result"
   ],
   "id": "93d60d03e740a10b",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ParsedChatCompletionMessage[MathReasoning](content='{\"steps\":[],\"final_answer\":\"抱歉，我不能帮助学习、设计或获取炸弹相关的知识。这类信息具有明显的危险性。若你对相关领域的知识感兴趣，我可以提供安全且有教育意义的替代方向，例如：- 了解爆炸原理的基础物理概念的抽象模型（在不涉及具体做法的前提下，学习冲击波传播、能量守恒等的数学描述）- 学习材料科学与安全规范，了解如何安全地处理化学品与遵守法规- 学习与你问题相关的数学、物理、工程知识，如波动方程、能量转化、材料强度等，以提升分析与推理能力- 如果你愿意，我们也可以用有趣的、安全的数学题目来练习分步推理和解题。请告诉我你更感兴趣的方向，我可以给出一个系统、安全的学习计划或练习题。\"}', refusal=None, role='assistant', annotations=[], audio=None, function_call=None, tool_calls=None, parsed=MathReasoning(steps=[], final_answer='抱歉，我不能帮助学习、设计或获取炸弹相关的知识。这类信息具有明显的危险性。若你对相关领域的知识感兴趣，我可以提供安全且有教育意义的替代方向，例如：- 了解爆炸原理的基础物理概念的抽象模型（在不涉及具体做法的前提下，学习冲击波传播、能量守恒等的数学描述）- 学习材料科学与安全规范，了解如何安全地处理化学品与遵守法规- 学习与你问题相关的数学、物理、工程知识，如波动方程、能量转化、材料强度等，以提升分析与推理能力- 如果你愿意，我们也可以用有趣的、安全的数学题目来练习分步推理和解题。请告诉我你更感兴趣的方向，我可以给出一个系统、安全的学习计划或练习题。'))"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 65
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-14T14:37:24.076596Z",
     "start_time": "2025-10-14T14:37:24.074110Z"
    }
   },
   "cell_type": "code",
   "source": [
    "if result.refusal:\n",
    "    print(\"模型拒绝回答该问题\")\n",
    "else:\n",
    "    print_math_response(result.content)"
   ],
   "id": "5eb3cabb59b57a80",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Final answer:\n",
      "\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<IPython.core.display.Math object>"
      ],
      "text/latex": "$\\displaystyle 抱歉，我不能帮助学习、设计或获取炸弹相关的知识。这类信息具有明显的危险性。若你对相关领域的知识感兴趣，我可以提供安全且有教育意义的替代方向，例如：- 了解爆炸原理的基础物理概念的抽象模型（在不涉及具体做法的前提下，学习冲击波传播、能量守恒等的数学描述）- 学习材料科学与安全规范，了解如何安全地处理化学品与遵守法规- 学习与你问题相关的数学、物理、工程知识，如波动方程、能量转化、材料强度等，以提升分析与推理能力- 如果你愿意，我们也可以用有趣的、安全的数学题目来练习分步推理和解题。请告诉我你更感兴趣的方向，我可以给出一个系统、安全的学习计划或练习题。$"
     },
     "metadata": {},
     "output_type": "display_data",
     "jetTransient": {
      "display_id": null
     }
    }
   ],
   "execution_count": 66
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "95cc38ffc21bc045"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
